package sz.szsmk.citizencard.ui.newversion.fragment

import android.app.Service
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Vibrator
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import com.google.zxing.WriterException
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_idcode.*
import kotlinx.android.synthetic.main.layout_idcode_fundescription.*
import kotlinx.android.synthetic.main.layout_idcode_l2.*
import kotlinx.android.synthetic.main.layout_idcode_qrcode.*
import org.greenrobot.eventbus.EventBus
import sz.szsmk.citizencard.DaggerApplication
import sz.szsmk.citizencard.R
import sz.szsmk.citizencard.entity.UploadHeadImgEntry
import sz.szsmk.citizencard.model.network.bean.response.BaseBean
import sz.szsmk.citizencard.model.network.bean.response.QRCodeBean
import sz.szsmk.citizencard.model.network.bean.response.QuerLeisureCardsInfoRes
import sz.szsmk.citizencard.model.network.bean.response.QuerLeisureCardsInfoRes.QuerLeisureCardsInfoBean
import sz.szsmk.citizencard.model.network.bean.response.ValidCardAuthorizationRes
import sz.szsmk.citizencard.model.network.bean.response.ValidCardAuthorizationRes.CardAuthrationInforsBean
import sz.szsmk.citizencard.mvp.BasePresenter
import sz.szsmk.citizencard.ui.activity.SelectImageActivity
import sz.szsmk.citizencard.ui.dialogs.LeisureYearCardsDialog
import sz.szsmk.citizencard.ui.dialogs.PrePermissionDialog.Companion.newInstance
import sz.szsmk.citizencard.ui.dialogs.UpLoadHeadImgDialog
import sz.szsmk.citizencard.ui.dzsmkavtivity.IdentityCodeActivity
import sz.szsmk.citizencard.ui.dzsmkfragment.AppBaseFragment
import sz.szsmk.citizencard.ui.newversion.fragment.presenter.IdCodePresenter
import sz.szsmk.citizencard.ui.newversion.fragment.view.IdCodeMvpView
import sz.szsmk.citizencard.util.*
import java.io.ByteArrayOutputStream
import java.io.File
import javax.inject.Inject

/**
 *  author : hyt
 *  date : 2020/9/2
 *  description : 身份码
 */
class IdCodeFragment: AppBaseFragment(), IdCodeMvpView {

    @Inject
    lateinit var idCodePresenter: IdCodePresenter

    override fun initPresenters(): Array<BasePresenter<*>>? {
        return arrayOf(idCodePresenter)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root = inflater.inflate(R.layout.fragment_idcode, container, false)
        component.inject(this)
        return root
    }

    override fun getTopTitle() = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    var isAutoStart = false


    override fun onResume() {
        super.onResume()

        layout_idcode_nol2.visibility = View.GONE
        layout_idcode_qrcode.visibility = View.GONE
        layout_idcode_funDescription.visibility = View.GONE

        //根据等级判断
        idCodePresenter.getLevel()
        if (isAutoStart) {
            ermCountDownTimer?.start()
        }
    }

    override fun lessL2() {
        //没有L2认证
        layout_idcode_nol2?.visibility = View.VISIBLE
        btn_toRealName.setOnClickListener {
            val bundle = Bundle()
            JumpUtils.jumptoNatvie(context, "RealNameActivity", 0, bundle)
        }
    }

    override fun validCardAuthorizationSucc(validCardAuthorizationRes: ValidCardAuthorizationRes) {

        //查询休闲年卡
        idCodePresenter.quryLeisureCards()

        //打开各种卡的信息
        layout_idcode_funDescription?.visibility = View.VISIBLE
        //填充数据
        initCardFunDescription(validCardAuthorizationRes)
        //添加事件
        initCardFunDescriptionEvent()
    }


    override fun onFail(baseBean: BaseBean) {
        showToast(baseBean.message)
    }

    private var infors = mutableListOf<CardAuthrationInforsBean>()
    var xxnkAuth: CardAuthrationInforsBean? = null
    private var tyhmUrl: String? = null
    private var whxfUrl: String? = null
    private var tyhmneedHead: String? = null
    private var whxfneedHead: String? = null
    private var tyhmsysLabel: String? = null
    private var whxfsysLabel: String? = null


    private fun initCardFunDescription(response: ValidCardAuthorizationRes) {
        infors = response.cardAuthrationInfors
        xxnkAuth = infors[0]
        val tyhmAuth: CardAuthrationInforsBean = infors[1]
        val whxfAuth: CardAuthrationInforsBean = infors[2]
        tyhmUrl = tyhmAuth.link_url
        whxfUrl = whxfAuth.link_url
        tyhmneedHead = tyhmAuth.need_header.toString()
        tyhmsysLabel = tyhmAuth.sys_label
        whxfneedHead = whxfAuth.need_header.toString()
        whxfsysLabel = whxfAuth.sys_label

        ll_cardBody.visibility = View.GONE
        if(!TextUtils.isEmpty(xxnkAuth?.leisureCardNo)){
            //卡号
            tv_cardNumber.text = "卡号:${xxnkAuth?.leisureCardNo}"
            ll_cardBody.visibility = View.VISIBLE
        }

        xxnkAuth.let{
            if(  (it?.isAuth.equals("1")    ||  it?.isAuth.equals("3")   ) ){
                sc_type.text= "套餐类型："+it?.packageName
                sc_endtime.text= "套餐有效期："+it?.expireDate
            }else {
                sc_type.visibility = View.INVISIBLE
                sc_endtime.visibility = View.INVISIBLE
            }
        }


        //休闲年卡授权状态判断

        //调试代码
//        xxnkAuth.setIsAuth("2");
//        xxnkAuth.setIsHavePhoto(0);

        //休闲年卡授权状态判断
        val xxIsAuth: String = xxnkAuth?.isAuth?:""
        when (xxIsAuth) {
            "1" -> {
                //休闲年卡已授权 1张卡
                auth_xxnk.text = "已授权"
                auth_xxnk.setBackgroundResource(R.drawable.shape_idcode_bg_green_r13)
                auth_xxnk.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_18b0a2))
                auth_xxnk.visibility = View.VISIBLE
                //查看可用景点
                ckjd_tv.visibility = View.VISIBLE
            }
            "2" -> {
                //休闲年卡未授权
                auth_xxnk.text = "去授权"
                auth_xxnk.setBackgroundResource(R.drawable.shape_idcode_bg_blue_r13)
                auth_xxnk.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_2184FA))
                auth_xxnk.visibility = View.VISIBLE
                select_card.visibility = View.GONE
                ckjd_tv.visibility = View.GONE
            }
            "3" -> {
                //休闲年卡未授权 多张卡
                auth_xxnk.text = "已授权"
                auth_xxnk.setBackgroundResource(R.drawable.shape_idcode_bg_green_r13)
                auth_xxnk.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_18b0a2))
                auth_xxnk.visibility = View.VISIBLE
                ckjd_tv.visibility = View.VISIBLE
                select_card.visibility = View.VISIBLE
            }
            "0" -> {
                //休闲年卡不存在 去办理
                auth_xxnk.text = "去办理"
                auth_xxnk.setBackgroundResource(R.drawable.shape_idcode_bg_blue_r13)
                auth_xxnk.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_2184FA))
                auth_xxnk.visibility = View.VISIBLE
                ckjd_tv.visibility = View.GONE
                select_card.visibility = View.GONE
            }
        }

        //已授权1张卡  和  已授权多张卡
        addHeadImg.visibility = View.GONE
        if (xxIsAuth == "1" || xxIsAuth == "3") {
            if (xxnkAuth?.isHavePhoto == 0) {
                addHeadImg.visibility = View.VISIBLE
            }
        }

        //体育惠民授权状态
        when (tyhmAuth.isAuth) {
            "1" -> {
                //体育惠民已授权
                auth_tyhm.text = "已授权"
                auth_tyhm.setBackgroundResource(R.drawable.shape_idcode_bg_green_r13)
                auth_tyhm.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_18b0a2))
                ckcg_tv.visibility = View.VISIBLE
                tyhm_rl.visibility = View.VISIBLE
                auth_tyhm.isEnabled = false
            }
            "2" -> {
                //体育惠民未授权
                auth_tyhm.text = "去授权"
                auth_tyhm.setBackgroundResource(R.drawable.shape_idcode_bg_blue_r13)
                auth_tyhm.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_2184FA))
                ckcg_tv.visibility = View.GONE
                tyhm_rl.visibility = View.VISIBLE
            }
            "0" -> {

            }
        }

        //文化消费授权状态判断
        when (whxfAuth.isAuth) {
            "1" -> {
                auth_whxf.text = "已授权"
                auth_whxf.setBackgroundResource(R.drawable.shape_idcode_bg_green_r13)
                auth_whxf.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_18b0a2))
                whxf_rl.visibility = View.VISIBLE
                cksj_tv.visibility = View.VISIBLE
                auth_whxf.isEnabled = false
            }
            "2" -> {
                auth_whxf.text = "去授权"
                auth_whxf.setBackgroundResource(R.drawable.shape_idcode_bg_blue_r13)
                auth_whxf.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_2184FA))
                cksj_tv.visibility = View.GONE
                whxf_rl.visibility = View.VISIBLE
            }
        }
    }



    var leisureYearCardsDialog: LeisureYearCardsDialog? = null

    private fun initCardFunDescriptionEvent() {
        record_id.setOnClickListener {
            //身份码使用记录
            val bundles = Bundle()
            val record = "${Constant.BASE_URL}app-front-end/#/other/sweepyards?access_token=" +
                    "${ACache.get(DaggerApplication.getIns()).getAsString("access_token")}"
            bundles.putString("url", record)
            JumpUtils.jumptoNatvie(context, "webView", 0, bundles)
        }
        select_card.setOnClickListener {
            //切换卡片
            changeCard()
        }

        addHeadImg.setOnClickListener {
            //添加头像   肯定是已授权的   在这之前 肯定是有刷新数据的 不用担心 有头像 还会显示添加头像
            val upLoadHeadImgDialog = UpLoadHeadImgDialog(requireContext())
            upLoadHeadImgDialog.upLoadHeadImgCallBack =  UPLoadHeadImgCallBackImpl(IdCodeFragment@ this)
            upLoadHeadImgDialog.show()
        }
        auth_xxnk.setOnClickListener {
            var xxnkTv = auth_xxnk.text.toString().trim()
            val bundle = Bundle()
            if (xxnkTv == "去办理") {
                val url3 = "${Constant.BASE_URL}app-front-end/#/card/main?access_token=" +
                        "${ACache.get(DaggerApplication.getIns()).getAsString("access_token")}"
                bundle.putString("url", url3)
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            } else if (xxnkTv == "去授权") {
                bundle.putString("type", "xxnk")
                JumpUtils.jumptoNatvie(context, "applicationAuthorActivity", 0, bundle)
            }
        }
        ckjd_tv.setOnClickListener {
            //查看可用景点
            val bundle3 = Bundle()
            val webUrl = "${Constant.BASE_URL}app-front-end/#/card/availableScenerySpot?access_token=" +
                    "${ACache.get(DaggerApplication.getIns()).getAsString("access_token")}&isMain=1"
            bundle3.putString("url", webUrl)
            JumpUtils.jumptoNatvie(context, "webView", 0, bundle3)
        }
        auth_whxf.setOnClickListener {
            //文化消费
            val whxfTv: String = auth_whxf.getText().toString().trim()
            val bundle = Bundle()
            if (whxfTv == "去授权") {
                bundle.putString(Constant.TYPE, "whxf")
                JumpUtils.jumptoNatvie(context, "applicationAuthorActivity", 0, bundle)
            } else if (whxfTv == "已授权") {
                auth_whxf.isEnabled = false
            }
        }
        cksj_tv.setOnClickListener {
            //查看可用商家
            var bundle = Bundle()
            if ("1" == whxfneedHead) {
                bundle.putString(Constant.TITLE, "")
            }

            if ("NOHEADER" == whxfsysLabel) {
                bundle.putString("url", "$whxfUrl?access_token=${ACache.get(DaggerApplication.getIns()).getAsString("access_token")}")
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            } else if ("HUIMIN" == whxfsysLabel) {
                if (tyhmUrl!!.contains("?")) {
                    bundle.putString("url", whxfUrl + "&" + Constant.EXTENT)
                } else {
                    bundle.putString("url", whxfUrl + "?" + Constant.EXTENT)
                }
                //苏体通需要自定义ua 传递标识
                bundle.putString("stt", "stt")
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)

            } else if ("ZZK" == whxfsysLabel) {
                bundle.putString("url", "$whxfUrl?access_token=${ACache.get(DaggerApplication.getIns()).getAsString("access_token")}")
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            } else {
                bundle.putString("url", whxfUrl)
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            }
        }

        auth_tyhm.setOnClickListener {
            //体育惠民 授权
            val tyhmTv: String = auth_tyhm.text.toString().trim()
            var bundle = Bundle()
            if (tyhmTv == "去授权") {
                bundle.putString(Constant.TYPE, "tyhm")
                JumpUtils.jumptoNatvie(context, "applicationAuthorActivity", 0, bundle)
            } else if (tyhmTv == "已授权") {
                auth_tyhm.isEnabled = false
            }
        }
        ckcg_tv.setOnClickListener {
            //查看可用场馆
            var bundle = Bundle()
            if ("1" == tyhmneedHead) {
                bundle.putString(Constant.TITLE, "")
            }
            if ("NOHEADER" == tyhmsysLabel) {
                bundle.putString("url", "$tyhmUrl?access_token=${ACache.get(DaggerApplication.getIns()).getAsString("access_token")}")
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            } else if ("HUIMIN" == tyhmsysLabel) {
                if (tyhmUrl!!.contains("?")) {
                    bundle.putString("url", tyhmUrl + "&" + Constant.EXTENT)
                } else {
                    bundle.putString("url", tyhmUrl + "?" + Constant.EXTENT)
                }
                //苏体通需要自定义ua 传递标识
                bundle.putString("stt", "stt")
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)

            } else if ("ZZK" == tyhmsysLabel) {
                bundle.putString("url", "$tyhmUrl?access_token=${ACache.get(DaggerApplication.getIns()).getAsString("access_token")}")
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            } else {
                bundle.putString("url", tyhmUrl)
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            }
        }


    }

    private var leisur_cards: List<QuerLeisureCardsInfoBean>? = null
    var lcTempForUpload: QuerLeisureCardsInfoBean? = null

    override fun quryLeisureCardsSuccess(response: QuerLeisureCardsInfoRes) {
        leisur_cards = response.leisur_cards

        ll_cardBody.visibility = View.GONE
        if(!TextUtils.isEmpty(xxnkAuth?.leisureCardNo)){
            //卡号
            tv_cardNumber.text = "卡号:${xxnkAuth?.leisureCardNo}"
            ll_cardBody.visibility = View.VISIBLE
        }

    }

    private fun changeCard() {
        var le: Int = leisur_cards?.size ?: 0
//        if (leisur_cards?.isNotEmpty()!!) { //同一账号 安卓手机被苹果手机挤掉，再点功能会空指针crash
        if (le != 0) {
            leisureYearCardsDialog = LeisureYearCardsDialog(requireContext(), { lcTemp, type -> //再打开一个 dialog
                if (type == 1) {
                    //上传头像
                    lcTempForUpload = lcTemp
                    val upLoadHeadImgDialog = UpLoadHeadImgDialog(requireContext())
                    upLoadHeadImgDialog.upLoadHeadImgCallBack = UPLoadHeadImgCallBackImpl(IdCodeFragment@ this)
                    upLoadHeadImgDialog.show()
                } else {
                    leisureYearCardsDialog!!.dismiss()
                    //绑定
                    if (StringUtils.isEmpty(lcTemp.cardNo)) {
                        idCodePresenter.cardnoAuthorization("")
                    } else {
                        idCodePresenter.cardnoAuthorization(lcTemp.cardNo)
                    }
                }
                //选卡后   直接 切换卡
                idCodePresenter.validCardAuthorization()
            }, leisur_cards)

            leisureYearCardsDialog!!.show()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == 100 && data != null) {
            val eventBusBean = UploadHeadImgEntry()
            eventBusBean.path = data.getStringExtra("imagePath")
            EventBus.getDefault().post(eventBusBean)
        }
    }


    class UPLoadHeadImgCallBackImpl(var idCodeFragment: IdCodeFragment) : UpLoadHeadImgDialog.UPLoadHeadImgCallBack {
        override fun callback(imageView: ImageView?) {
            //自定义弹窗
            val dialog = newInstance {
                //授权
                idCodeFragment.realPermission()
            }
            dialog.show(idCodeFragment.childFragmentManager , "permission")

        }

        override fun upLoadImg(path: String?) {
            path?.let {
                idCodeFragment.upLoad(it)
            }
        }
    }

    private fun realPermission(){
        XXPermissions.with(this)
            .permission(
                Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA
            )
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    if (all) {
                        requireActivity()?.startActivityForResult(Intent(requireContext(), SelectImageActivity::class.java), 100)
                    } else {
                        showToast("获取部分权限成功，但部分权限未正常授予")
                    }
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    if (never) {
                        showToast("被永久拒绝授权，请手动授予权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(requireActivity(), permissions)
                    } else {
                        showToast("获取权限失败")
                    }
                }
            })
    }

    //以下为上传头像
    private fun upLoad(path: String) {
        val files = IdentityCodeActivity.compressImage(PhotoUtils.getBitmapFromUri(Uri.fromFile(File(path)), context))
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = false
        val bitmaptemp = BitmapFactory.decodeFile(files.absoluteFile.toString())
        val photo: String = Bitmap2StrByBase64(bitmaptemp)!!
        idCodePresenter.upLoadPic(xxnkAuth!!.leisureCardNo, photo)
    }

    override fun getUploadPic() {
        //头像上传成功
        showToast("头像上传成功")
        //重新刷新数据
        idCodePresenter.validCardAuthorization()
        idCodePresenter.quryLeisureCards()
        leisureYearCardsDialog!!.dismiss()
    }
    private var qrCodeMsg: String? = null
    var imageView_width = 0

    override fun getQRCodeSuccess(response: QRCodeBean) {

        //显示界面
        //打开二维码
        layout_idcode_qrcode?.visibility = View.VISIBLE

        //初始化 点击事件
        iv_idCode.setOnClickListener {
            idCodePresenter.getQrNumber()
            if (ermCountDownTimer != null) {
                ermCountDownTimer?.start()
            }
            lin_refresh?.isEnabled = false
            iv_idCode?.isEnabled = false
            autoRefreshCountDownTimer?.cancel()
        }

        //初始化 二维码数据
        //震动 计时器
        initVibratorAndCountDownTimer()
        //显示二维码
        iv_idCode.post {
            imageView_width = iv_idCode.measuredWidth

            if (!StringUtils.isBlank(response.qr_code)) {
                qrCodeMsg = response.qr_code
                //获取图片展示不出
                try {
                    val qrCodeImg = QrCodeUtils.createQRCode(response.qr_code, imageView_width)
                    //常亮
                    activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
                    ScrennLight.setBrightness(activity,255)
                    iv_idCode.setImageBitmap(qrCodeImg)
                } catch (e: WriterException) {
                    e.printStackTrace()
                }
                if (!StringUtils.isBlank(response.picture)) {

                    //loadImageSimpleTarget(response.picture)
                    refresh_icon.setImageResource(R.drawable.adress_check)
                    refresh_state.text = "已刷新"
                    if (ermCountDownTimer != null) {
                        isAutoStart = true
                        ermCountDownTimer?.start()
                    }
                } else {
                    try {
                        response.qr_code
                        var logo = BitmapFactory.decodeResource(resources, R.drawable.user_icon)
//                        if (AndroidDeviceInfo.getPhoneProducer().equals("Xiaomi")||AndroidDeviceInfo.getPhoneProducer().equals("Redmi")){
//                            logo=null
//                        }
                        val qrCodeImg = QrCodeUtils.createQRCode(null, response.qr_code, imageView_width, imageView_width / 5)
                        iv_idCode.setImageBitmap(qrCodeImg)
                        refresh_icon.setImageResource(R.drawable.adress_check)
                        refresh_state.text = "已刷新"
                        if (ermCountDownTimer != null) {
                            isAutoStart = true
                            ermCountDownTimer?.start()
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }


    fun Bitmap2StrByBase64(bit: Bitmap): String? {
        val bos = ByteArrayOutputStream()
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos) //参数100表示不压缩
        val bytes = bos.toByteArray()

        //自带base64 和后台不一致
        return Base64.encode(bytes)
    }

    private val target: SimpleTarget<Bitmap> = object : SimpleTarget<Bitmap>() {
        override fun onResourceReady(bitmap: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {
            //这里我们拿到回掉回来的bitmap，可以加载到我们想使用到的地方
            try {
                val qrCodeImg = QrCodeUtils.createQRCode(bitmap, qrCodeMsg, imageView_width, imageView_width / 5)
                iv_idCode.setImageBitmap(qrCodeImg)
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun loadImageSimpleTarget(url: String) {
        Glide.with(activity)
            .load(url)
            .asBitmap() //强制转换Bitmap
            .into(target)
    }

    var mVibrator: Vibrator ?=null

    private fun initVibratorAndCountDownTimer(){
        //振动器
        mVibrator = activity?.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator?

        ermCountDownTimer   = object: CountDownTimer(3 * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
            }

            override fun onFinish() {
                lin_refresh?.isEnabled = true
                iv_idCode?.isEnabled = true
                refresh_icon?.setImageResource(R.mipmap.icon_refresh)
                refresh_state?.text = "请点击二维码刷新"
                autoRefreshCountDownTimer?.start()
            }
        }
        autoRefreshCountDownTimer = object:CountDownTimer(60 * 1000, 1000){
            override fun onTick(millisUntilFinished: Long) {
            }

            override fun onFinish() {
                lin_refresh?.isEnabled = false
                iv_idCode?.isEnabled = false
                refresh_icon?.setImageResource(R.drawable.adress_check)
                refresh_state?.text = "已刷新"

                if (ermCountDownTimer != null) {
                    ermCountDownTimer?.start()
                    mVibrator?.vibrate(1000)
                }
            }

        }
    }

    var ermCountDownTimer:CountDownTimer ?= null

    var autoRefreshCountDownTimer :CountDownTimer ?= null

    override fun onPause() {
        super.onPause()
    }

    override fun onDestroyView() {
        super.onDestroyView()

        if (ermCountDownTimer != null) {
            ermCountDownTimer?.cancel()
            ermCountDownTimer = null
        }
        if (autoRefreshCountDownTimer != null) {
            autoRefreshCountDownTimer?.cancel()
            autoRefreshCountDownTimer = null
        }

        if (null != mVibrator) {
            mVibrator?.cancel()
            mVibrator = null
        }
    }

}